package stu.day25_day32.day27;

import stu.day25_day32.day25.all.TreeNode;

public class hw2 {
    TreeNode f;
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        isNode(root,p,q);
        return f;

    }

    public TreeNode isNode(TreeNode node, TreeNode p, TreeNode q){

        if(node==null||node==p||node==q){
            return node;
        }
        TreeNode left = isNode(node.left,p,q);
        TreeNode right = isNode(node.right,p,q);

        if(left!=null&&right!=null){
            f = node;
            return null;
        }
        if(left==null&&right==null){
            if(node.val==p.val||node.val==q.val){
                return node;
            }
            return null;
        }


        if(node.val==p.val||node.val==q.val){
            f = node;
            return null;
        }
        return left==null?right:left;

    }

}
